<template>
    <Dialog :title="comInfo.name" :show="true" @close="cancel" :width="350" :height="450" :left="uiLeft" :top="uiTop">
        <div class="box">
            <!-- 功能按钮 -->
            <div class="cimrts-menu">
                <div class="menu-left">
                    <FucMenuList :menuList="layerMenuList" @clickComponent="clickComponent" :isDisabled="false"
                        :isChecked="false" />
                </div>
                <div class="menu-right">
                    <el-select v-model="colorMode" placeholder="请选择着色模式" style="width: 150px">
                        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </div>

            </div>
            <LayerTree :arr="tranformDataRef" @checkTree="checkTree" ref="layerTree" />
        </div>
    </Dialog>
    <TooltipCom v-if="currentDialog == 'save'" :content="'确定保存吗？'" :title="'保存'" :isVisible="true"
        @close="currentDialog = undefined" @confirm="saveConfirm" />
</template>
<script setup lang="ts">
import Dialog from "@/components/Dialog.vue";
import { onMounted, ref, onBeforeUnmount, computed, watch, shallowRef } from "vue";
import { getProjectManager } from "@/scripts/getProjectManager";
import {
    createVueDisposer,
    toVR,
} from "earthsdk-ui";
import { layerMenuList } from "@/scripts/menu/cimrts/layerMenuList";
import LayerTree from "@/components/virtualbatch/LayerTree.vue";
import { ElMessage } from "element-plus";
import TooltipCom from "@/components/common/TooltipCom.vue";
import FucMenuList from "@/components/common/FucMenuList.vue";
import { ESJFeatureStyleType } from "earthsdk3";
import { VirtualLayer } from "../../scripts/cimrtsManager/virtualLayer";

const props = withDefaults(defineProps<{ comInfo: any }>(), {});
const emits = defineEmits(["cancel"]);
const cancel = () => {
    emits("cancel", props.comInfo.id);
};
const uiLeft = ref(document.body.clientWidth - 10 - 350);
const uiTop = ref(60);


const d = createVueDisposer(onBeforeUnmount);
const objm = getProjectManager();
const eSRtsTileset = objm.cimrtsManager.eSRtsTileset
const virtualLayer = objm.cimrtsManager.virtualLayer as VirtualLayer

const options = [
    {
        value: "HIGHLIGHT",
        label: "默认颜色",
    },
    {
        value: "REPLACE",
        label: "图层纯色",
    },
    {
        value: "MIX",
        label: "图层混色",
    },
];

// 保存 
const save = () => {
    return new Promise((resolve) => {
        currentDialog.value = "save";
        const d = virtualLayer.dialogEvent.disposableOnce(async (val: string) => {
            d();
            if (val == "confirm") {
                const res = await eSRtsTileset.saveLayerConfig();
                // @ts-ignore
                if (res.status == "ok") {
                    ElMessage.success(`保存成功`);
                }
            }
            currentDialog.value = undefined;
            resolve("ok");
        });
    });
};

// 当前打开的弹框组件
const currentDialog = ref<undefined | string>(undefined);
const layerTree = ref<any>(null)

// 鼠标点击组件
const clickComponent = (item: any) => {
    switch (item.name) {
        case "刷新":
            virtualLayer.getTreeList();
            break;
        case "保存":
            save()
            break;
        case "生成随颜色":
            layerTree.value.random()
            break;
        case "恢复初始颜色":
            layerTree.value.reset()
            break;
    }
}
const colorMode = ref(eSRtsTileset.colorBlendMode ?? "HIGHLIGHT");

watch(colorMode, (val: any) => {
    console.log(val, "val");
    eSRtsTileset.colorBlendMode = val;
});

const tranformDataRef = toVR<any>(d, [virtualLayer, "tranformData"]);

const checkTree = (finalConfig: any) => {
    eSRtsTileset.layerConfig = finalConfig;
};

// 保存 弹出框确定按钮
const saveConfirm = () => {
    virtualLayer.dialogEvent.emit("confirm");
}
onMounted(() => {
    virtualLayer.init()
})

const colorToRGBA = (color: string) => {
    color = color.toLocaleLowerCase();
    let rgba = [255, 255, 255, 1];
    // 十六进制颜色值转换为RGBA
    if (color.startsWith('#')) {
        if (color.length === 4) {
            // #rgb
            let r = parseInt(color[1] + color[1], 16);
            let g = parseInt(color[2] + color[2], 16);
            let b = parseInt(color[3] + color[3], 16);
            rgba = [r, g, b, 1];
        } else if (color.length === 7) {
            // #rrggbb
            let r = parseInt(color.substring(1, 3), 16);
            let g = parseInt(color.substring(3, 5), 16);
            let b = parseInt(color.substring(5, 7), 16);
            rgba = [r, g, b, 1];
        }
    }
    // RGBA颜色值转换为RGBA
    else if (color.startsWith('rgba')) {
        let match = color.match(/^rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*([\d.]+)\s*\)$/);
        if (match) {
            let r = parseInt(match[1]);
            let g = parseInt(match[2]);
            let b = parseInt(match[3]);
            let a = parseFloat(match[4]);
            rgba = [r, g, b, a];
        }
    }
    // RGB颜色值转换为RGBA
    else if (color.startsWith('rgb')) {
        let match = color.match(/^rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/);
        if (match) {
            let r = parseInt(match[1]);
            let g = parseInt(match[2]);
            let b = parseInt(match[3]);
            rgba = [r, g, b, 1];
        }
    } else {
        console.error('color类型只能为#rrggbb、#rgb、rgba(r,g,b,a)、rgb(r,g,b)')
    }
    return [rgba[0] / 255, rgba[1] / 255, rgba[2] / 255, rgba[3]] as [number, number, number, number];
}

onBeforeUnmount(() => {
    eSRtsTileset.colorBlendMode = "HIGHLIGHT"
    // layerTree.value.reset()

    const layerConfig = eSRtsTileset.layerConfig as any;;
    if (!layerConfig || !layerConfig.length) return;
    if (objm.activeViewer.typeName != "ESCesiumViewer") {
        const options: ESJFeatureStyleType = []
        layerConfig.forEach((e: any) => {
            // @ts-ignore
            const filterConfig = layerConfig.filter(c => c.dataset == e.dataset)

            // 说明图层是数据集
            if (filterConfig.length == 1) {
                options.push({
                    condition: [{
                        field: "dataset",
                        op: "==",
                        value: e.dataset
                    }],
                    color: colorToRGBA('rgb(255,255,255)'),
                    show: e.value.visible
                })
            } else {
                options.push({
                    condition: [{
                        field: "layer",
                        op: "==",
                        value: e.layer
                    }, {
                        field: "dataset",
                        op: "==",
                        value: e.dataset
                    }],
                    color: colorToRGBA('rgb(255,255,255)'),
                    show: e.value.visible
                })
            }
        });
        eSRtsTileset.setFeatureStyle(options);
    }
})
</script>

<style scoped>
.box {
    box-sizing: border-box;
    width: 100%;
    height: 100%;
}

.cimrts-menu {
    background-color: #f0f0f0;
    width: calc(100%);
    height: 40px;
    display: flex;
    justify-content: space-around;
    align-items: center;

}

.menu-left {
    width: 50%;
}

.panel-list {
    width: 40px;
    height: 40px;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 3px;
    cursor: pointer;
}

.panel-list>img {
    width: 20px;
    height: 20px;
}


.hover {
    background-color: #cfd8f3;
}
</style>